package edu.del.springbootredisbusinesspractice.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SnowflakeIdGenerator {
    // 创建时间戳的起始时间
    private final static long START_TIMESTAMP = 1609459200000L;

    // 各部分位数
    private final static long SEQUENCE_BIT = 12;
    private final static long MACHINE_BIT = 10;

    // 最大值
    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);

    // 各部分偏移量
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long TIMESTAMP_LEFT = SEQUENCE_BIT + MACHINE_BIT;

    // 机器ID
    private long machineId;
    // 序列号
    private long sequence = 0;
    // 上次时间戳
    private long lastTimestamp = -1L;

    public SnowflakeIdGenerator(@Value("${machine.id:1}") long machineId) {
        if (machineId > ~(-1L << MACHINE_BIT)) {
            throw new IllegalArgumentException("机器ID超出范围");
        }
        this.machineId = machineId;
    }

    /**
     * 生成下一个ID的方法
     * @return 生成的唯一ID
     */
    public synchronized long nextId() {
         // 获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();

        // 时钟回拨检查
        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨异常");
        }

        // 同一毫秒内序列号递增
        if (currentTimestamp == lastTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 序列号用完，等待下一毫秒
            if (sequence == 0) {
                currentTimestamp = getNextTimestamp();
            }
        } else {
            sequence = 0;
        }

        lastTimestamp = currentTimestamp;

        return (currentTimestamp - START_TIMESTAMP) << TIMESTAMP_LEFT
                | machineId << MACHINE_LEFT
                | sequence;
    }

    /**
     * 获取下一个时间戳
     * 该方法用于获取一个大于上一次时间戳的新时间戳
     * 如果当前时间戳小于或等于上一次时间戳，则循环获取新的时间戳
     *
     * @return 返回一个大于lastTimestamp的时间戳
     */
    private long getNextTimestamp() {
        // 获取当前系统时间戳
        long timestamp = System.currentTimeMillis();
        // 循环直到获取到比lastTimestamp大的时间戳
        while (timestamp <= lastTimestamp) {
            // 重新获取当前系统时间戳
            timestamp = System.currentTimeMillis();
        }
        // 返回获取到的新时间戳
        return timestamp;
    }
}
